package com.misty.blog.controller.blogController;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.misty.blog.bean.param.BwcParam;
import com.misty.blog.bean.param.comment.CommentSaveParam;
import com.misty.blog.service.CommentService;
import com.misty.blog.service.MessageService;
import com.misty.blog.service.UsersService;
import com.misty.common.bean.Result;
import com.misty.dao.domain.Comment;
import com.misty.dao.domain.Message;
import com.misty.dao.domain.Users;
import com.misty.dao.dto.CommentDto;
import com.misty.dao.dto.MessageDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/fore/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private UsersService usersService;

    @GetMapping("/{id}")
    public Result<?> blogWithComment(@PathVariable(name = "id") Integer blogId,BwcParam param){
        //查询
        Result result = commentService.blogWithComment(blogId);
        if(result.getCode() != 0){
            return result;
        }
        List<CommentDto> commentDtoList = (List<CommentDto>)result.getData();
        for (CommentDto commentDto : commentDtoList) {
            Integer commentId = commentDto.getId();
            Result<?> messageResult = messageService.selectMessagePage(param.getPageNum(), param.getPageSize(), commentId);
            if(messageResult.getCode() != 0){
                return Result.error("查询该博客用户以及评论失败！");
            }
            Page<MessageDto> messageDtoPage = (Page<MessageDto>)messageResult.getData();
            List<MessageDto> records = messageDtoPage.getRecords();
            commentDto.setMessageList(records);
        }

        return Result.success("查询该博客用户以及评论成功！",commentDtoList);
    }


    @PreAuthorize("hasAuthority('fore/comment')")
    @PostMapping("/save")
    public Result<?> commentSave(@RequestBody CommentSaveParam param){

        //查询是否有此用户
        Users users = new Users();
        users.setUsername(param.getUsername());
        Users selectOne = usersService.selectOne(users);
        if(ObjectUtil.isEmpty(selectOne)){
            return Result.error("评论失败！");
        }

        //保存评论
        Comment comment = new Comment();
        comment.setContent(param.getContent());
        comment.setBlogId(param.getBlogId());
        comment.setUserId(selectOne.getId());
        int saveComment = commentService.saveComment(comment);
        if(saveComment == 0){
            return Result.error("评论失败！");
        }
        return Result.success("评论成功！");
    }

    @PreAuthorize("hasAuthority('fore/comment')")
    @DeleteMapping("/delete")
    @Transactional(transactionManager = "mistyTransactionManager")
    public Result<?> commentDelete(@RequestParam Integer id){
        //删除评论
        int deleteById = commentService.commentDelete(id);
        if(deleteById == 0){
            return Result.error("删除评论失败！");
        }

        //查询评论下是否有回复
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Message::getCommentId,id);
        long count = messageService.count(queryWrapper);
        if(count <= 0 ){
//            没有回复则直接返回成功
            return Result.success("删除评论成功！");
        }

        //删除对应评论下的回复
        UpdateWrapper<Message> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(Message::getCommentId,id);
        boolean remove = messageService.remove(updateWrapper);
        if(!remove){
            return Result.error("删除评论失败！");
        }
        return Result.success("删除评论成功！");
    }


}
